/* eslint-disable import/no-anonymous-default-export */
/*
 * @Author: 余其方 448919239@qq.com
 * @Date: 2022-08-02 20:53:07
 * @LastEditors: 余其方 448919239@qq.com
 * @LastEditTime: 2022-09-01 16:05:18
 * @FilePath: /redux-demo/src/store/reducer.js
 * @Description:
 *
 * Copyright (c) 2022 by 余其方 448919239@qq.com, All Rights Reserved.
 */
import {
  CHANGE_INPUT_VALUE,
  CHANGE_LIST_VALUE,
  DELETE_LIST_ITEM,
  INIT_LIST_ACTION,
} from "./actionTypes";

// 默认数据
const defaultState = {
  inputValue: "",
  list: []
};

export default (state = defaultState, action) => {
  // state是整个仓库存储的数据，action是store传递来的一个对象

  if (action.type === CHANGE_INPUT_VALUE) {
    return { ...state, inputValue: action.value };
  }
  if (action.type === CHANGE_LIST_VALUE) {
    const newState = JSON.parse(JSON.stringify(state));
    newState.list.push(newState.inputValue);
    newState.inputValue = "";
    return newState;
  }
  if (action.type === DELETE_LIST_ITEM) {
    const newState = JSON.parse(JSON.stringify(state));
    newState.list.splice(action.index, 1);
    return newState;
  }
  if (action.type === INIT_LIST_ACTION) {
    return action.data;
  }
  return state;
};

// reducer可以接受state，但是绝对不能改变state
// reducer.js返回一个数据和方法
